package org.lisen.mvc.framework;

import java.io.InputStream;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public final class ConfigModelFactory {

	private static final String CONFIG_FILE_PATH = "/config.xml";

	private static ConfigModel configModel = new ConfigModel();

	private ConfigModelFactory() {
	}
	
	static {
		try {
			InputStream is = ConfigModelFactory.class.getResourceAsStream(CONFIG_FILE_PATH);

			SAXReader reader = new SAXReader();
			Document document = reader.read(is);

			Element configElement = document.getRootElement();
			List<Element> actionElementList = configElement.selectNodes("/config/action");
			for (Element actionElement : actionElementList) {
				String path = actionElement.attributeValue("path");
				String type = actionElement.attributeValue("type");

				ActionModel actionModel = new ActionModel();
				actionModel.setPath(path);
				actionModel.setType(type);
				configModel.put(actionModel);

				List<Element> forwardElementList = actionElement.selectNodes("forward");
				for (Element forwardElement : forwardElementList) {
					String name = forwardElement.attributeValue("name");
					String forwardPath = forwardElement.attributeValue("path");
					String redirect = forwardElement.attributeValue("redirect");

					ForwardModel forwardModel = new ForwardModel();
					forwardModel.setName(name);
					forwardModel.setPath(forwardPath);
					forwardModel.setRedirect(redirect);
					actionModel.put(forwardModel);
				}
			}

		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static ConfigModel getConfigModel() {
		return configModel;
	}

	public static void main(String[] args) {
		ConfigModel configModel = getConfigModel();
		ActionModel actionModel = configModel.find("/loginAction");
		ForwardModel forwardModel = actionModel.find("success");
		System.out.println(forwardModel.getPath());
	}
	
}
